/**
 * @description utils controller
 * @author 刘煎蛋
 */

const path = require('path')
const { ErrorModel, SuccessModel } = require('../model/ResModel')
const { uploadFileSizeFailInfo } = require('../model/ErrorInfo')
const fse = require('fs-extra')

const DIST_FOLDER_PATH = path.join(__dirname,'..','..','uploadFiles');
const MIX_SIZE = 1024 * 1024 * 1024;

/**
 * 
 * @param {*} name 文件名字
 * @param {*} size 文件大小
 * @param {*} filePath 文件路径
 * @param {*} type  文件类型
 */
async function saveFile({ name, size, filePath, type }) {
    if ( size > MIX_SIZE ) {
        // 删除文件资源
        await fse.remove(filePath);
        return new ErrorModel(uploadFileSizeFailInfo);
    }

    const fileName = Date.now() + '.' + name;
    const distFilePath = path.join(DIST_FOLDER_PATH, fileName);
    await fse.move(filePath, distFilePath);

    return new SuccessModel({
        url: '/' + fileName
    })
}

module.exports = saveFile